import axios from 'axios'
import { Toast } from 'vant';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import qs from 'qs'
import store from '@/store'

// 创建 axios 实例
const request = axios.create({
  timeout: 15000 // 请求超时时间
})

// NProgress.inc(0.2)
NProgress.configure({ showSpinner: false })

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    // NProgress.done()
    if (error.response.status === 400) {
      Toast({
        message: '请求参数错误',
        type: 'error'
      })
    }
    if (error.response.status === 403) {
      Toast({
        message: '没有权限，请联系管理员',
        type: 'error'
      })
    }
    if (error.response.status === 404) {
      Toast({
        message: '请求资源不存在',
        type: 'error'
      })
    }
    if (error.response.status >= 500) {
      Toast({
        message: '服务器报告错误',
        type: 'error'
      })
    }
    if (error.response.status === 0) {
      Toast({
        message: '请求失败',
        type: 'error'
      })
    }
  } else if (error.request) {
    Toast({
      message: '服务器异常',
      type: 'error'
    })
  } else {
    Toast({
      message: '请求失败',
      type: 'error'
    })
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use((config) => {
  // console.log('config', config)
  // NProgress.start() // start progress bar

  const baseUrl = process.env.VUE_APP_BASE_URL
  const url = config.url
  if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
    config.url = baseUrl + config.url
  }
  const configData = {
    token: store.state.token || sessionStorage.getItem('cspace-token'),
  }
  if (config.method === 'get') {
    config.params = {
      ...configData,
      request: {
        ...config.data.request
      }
    }
  } else {
    config.data = qs.stringify({
      ...configData,
      request: JSON.stringify(config.data.request)
    })

  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  // NProgress.done()
  if (response.data.errorCode === 0 || response.config.responseType === 'blob') {
    return response.data
  } else {
    if (response.data.errorCode === 401) {
      // fn_token__remove()
      // router.push('/user/login')
      Toast({
        message: '登录已过期，请重新登录',
        type: 'warning'
      })
      return response.data
    } else {
      if (response.data.type) {
        return response.data
      }
      Toast({
        message: response.data.errorMessage,
        type: 'error'
      })
      return response.data
    }
  }
}, errorHandler)

export default request
